package commons.base.elasticsearch;

import java.io.IOException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.List;

import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import commons.base.db.Databases;

public class Demo1 {

	public static void main(String[] args) throws Exception{
		t11();
	}
	
	public static void t1()throws Exception{
		ESClient esClient = new ESClient("kamuy", "10.130.130.249", 9300);
		
		SearchResponse response = esClient.search("kamuy", "user", 10, "captainName", "火车");
		SearchHits hits = response.getHits();
		for (SearchHit hit : hits) {
			System.out.println("分数(score):" + hit.getScore() +", " + hit.getId()+ "," + hit.getSource().get("captainName") + "," + hit.getSource().get("username"));
//			System.out.println("===" + hit.getHighlightFields().get("captainName").toString());
		}

		esClient.close();
	}
//	private static final DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
	public static void t11()throws Exception{
		ESClient esClient = new ESClient("kamuy", "10.130.130.249", 9300);
		
//		LocalDateTime.parse("2016-03-31 00:00:00", format).to
		
		
		long t1 = Instant.parse("2016-03-31T00:00:00.00Z").toEpochMilli();
		long t2 = Instant.parse("2016-03-31T23:59:59.00Z").toEpochMilli();
		QueryBuilder qb = QueryBuilders.boolQuery()
				      .must(QueryBuilders.termQuery("userId", 20000))
				      .must(QueryBuilders.rangeQuery("createTime").gt(t1).lt(t2));
				  
		long start = System.currentTimeMillis();
		SearchResponse response = esClient.search("diamond_record_index", "diamond_record", qb, 1000);
		long end = System.currentTimeMillis();
		SearchHits hits = response.getHits();
		for (SearchHit hit : hits) {
			System.out.println(hit.getSource().get("userId") + "," + hit.getSource().get("changeAmount") + "," + Instant.ofEpochMilli((long)hit.getSource().get("createTime")));
		}
		
		esClient.close();
		
		System.err.println("exec time : " + (end - start));
	}
	
	public static void t2()throws Exception{
		ESClient esClient = new ESClient("kamuy", "10.130.130.249", 9300);
		
		for(int i=8; i<=99; i++){
			String sql = "select id,username,captainName from user_" + i;
			List<UserDoc> list = Databases.getDatabase("132").queryModelList(sql, UserDoc.class);
			
			BulkOp bulkOp = esClient.newBulk(100);
			for(UserDoc userDoc : list){
				bulkOp.update(toRequestBuilder(esClient, userDoc));
			}
			
			if(!bulkOp.isEmpty()){
				bulkOp.execute();
			}
			System.err.println("finish. size=" + list.size());
		}
		
		esClient.close();
	}
	public static void t3()throws Exception{
		ESClient esClient = new ESClient("kamuy", "10.130.130.249", 9300);
		
		long start = System.currentTimeMillis();
		for(int i=0; i<=99; i++){
			String sql = "select * from diamond_record_" + i;
			List<DiamondRecordDoc> list = Databases.getDatabase("132").queryModelList(sql, DiamondRecordDoc.class);
//			System.err.println(list.get(0).getUserId() + ", " + list.get(0).getCreateTime().getTime() + "," + list.get(0).getCreateTime());
			BulkOp bulkOp = esClient.newBulk(100);
			for(DiamondRecordDoc doc : list){
				bulkOp.update(toRequestBuilder(esClient, doc));
			}
			
			if(!bulkOp.isEmpty()){
				bulkOp.execute();
			}
			System.err.println("finish. size=" + list.size());
		}
		long end = System.currentTimeMillis();
		System.err.println("exec time: " + ((end - start)/1000));
		
		esClient.close();
	}
	private static IndexRequestBuilder toRequestBuilder(ESClient esClient, UserDoc userDoc) throws IOException{
		XContentBuilder sourceBuilder = XContentFactory.jsonBuilder()
				.startObject()
				.field("username", userDoc.getUsername())
				.field("captainName", userDoc.getCaptainName())
				.endObject()
				;
		
		return esClient.getClient().prepareIndex("kamuy", "user").setId(userDoc.getId()).setSource(sourceBuilder);
	}
	private static IndexRequestBuilder toRequestBuilder(ESClient esClient, DiamondRecordDoc doc) throws IOException{
		XContentBuilder sourceBuilder = XContentFactory.jsonBuilder()
				.startObject()
				.field("userId", doc.getUserId())
				.field("changeAmount", doc.getChangeAmount())
				.field("beforeAmount", doc.getBeforeAmount())
				.field("afterAmount", doc.getAfterAmount())
				.field("changeSource", doc.getChangeSource())
				.field("createTime", doc.getCreateTime().getTime())
				.endObject()
				;
		
		return esClient.getClient().prepareIndex("diamond_record_index", "diamond_record").setSource(sourceBuilder);
	}
	
	public static class UserDoc{
		private String id;
		private String username;
		private String captainName;
		
		public UserDoc() {
			super();
		}

		public UserDoc(String id, String username, String captainName) {
			super();
			this.id = id;
			this.username = username;
			this.captainName = captainName;
		}
		
		public String getId() {
			return id;
		}
		public void setId(String id) {
			this.id = id;
		}
		public String getUsername() {
			return username;
		}
		public void setUsername(String username) {
			this.username = username;
		}
		public String getCaptainName() {
			return captainName;
		}
		public void setCaptainName(String captainName) {
			this.captainName = captainName;
		}
		
	}
	
	public static class DiamondRecordDoc{
		private long userId;
		private int changeAmount;
		private int beforeAmount;
		private int afterAmount;
		private String changeSource;
		private Timestamp createTime;
		
		public long getUserId() {
			return userId;
		}
		public void setUserId(long userId) {
			this.userId = userId;
		}
		public int getChangeAmount() {
			return changeAmount;
		}
		public void setChangeAmount(int changeAmount) {
			this.changeAmount = changeAmount;
		}
		public int getBeforeAmount() {
			return beforeAmount;
		}
		public void setBeforeAmount(int beforeAmount) {
			this.beforeAmount = beforeAmount;
		}
		public int getAfterAmount() {
			return afterAmount;
		}
		public void setAfterAmount(int afterAmount) {
			this.afterAmount = afterAmount;
		}
		public String getChangeSource() {
			return changeSource;
		}
		public void setChangeSource(String changeSource) {
			this.changeSource = changeSource;
		}
		public Timestamp getCreateTime() {
			return createTime;
		}
		public void setCreateTime(Timestamp createTime) {
			this.createTime = createTime;
		}
		
	}

}
